<?php

namespace App\Http\Controllers\WF\Systems;

use DB;
use Config;
use Hash;
use Carbon\Carbon;
use Overtrue\Pinyin\Pinyin;
use Ramsey\Uuid\Uuid;
use App\Http\Controllers\WF\ApiController;
use App\Http\Controllers\Wf\Common\Share;
use Illuminate\Http\Request;
use App\Eloqumd\Wf\WfCompany;
use App\Eloqumd\Wf\WfUser;
use App\Http\Requests\WF\CompanyRequest;
use App\Http\Requests\WF\OrgRequest;

class CompanyController extends ApiController
{
    /**
     * 获取公司架构树
     *
     * @name    getCompanyListTree
     *
     * @param   integer     $companyId      单位平台ID
     *
     * @return 	array                       返回结果
     */
    public function getCompanyListTree(Request $request)
    {
        $companyId = $request->input('companyId', 0);
        $jsonData = WfCompany::find($companyId)->toArray();
        $jsonData['label'] = $jsonData['name'];
        $jsonData['children'] = $this->getOrgTree($companyId);

        return $this->jsonReturns(10000, $this->success, [$jsonData]);
    }

    protected function getOrgTree($parent_id)
    {
        $tree =  WfCompany::where('parent_id', $parent_id)->get()->toArray();

        $returnTree = [];
        if ($tree) {
            foreach ($tree as $key => $val) {
                $val['label'] = $val['name'];
                $subMenu = $this->getOrgTree($val['id']);
                foreach ($subMenu as $k => $v) {
                    $val['children'][] = $v;
                }
                $returnTree[] = $val;
            }
        } else {
            return [];
        }

        return $returnTree;
    }

    /**
     * 单位平台列表
     *
     * @name    getCompanyList
     *
     * @param   integer     $page           当前页
     * @param   integer     $limit          每页大小
     * @param   mixed      $keyword         快捷搜索
     *
     * @return 	array                       返回结果
     */
    public function getCompanyList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $request->input('keyword', '');
        $orWhere = [];
        $where[] = ['parent_id', '=', 0, 'AND'];
        $where[] = ['isdel', '=', 0, 'AND'];
        if ($this->apiUser['user_type'] == 0) {
            // 快捷搜索-名称,简称,编码,标识
            if ($keyword) {
                $orWhere[] = ['name', 'like', "%{$keyword}%", 'AND'];
                $orWhere[] = ['short_name', 'like', "%{$keyword}%", 'OR'];
                $orWhere[] = ['code', 'like', "%{$keyword}%", 'OR'];
                $orWhere[] = ['tag', 'like', "%{$keyword}%", 'OR'];
            }
        } else {
            $where[] = ['id', '=', $this->apiUser['company_id'], 'AND'];
        }

        $totalCount = WfCompany::where($where)
            ->where(function ($query) use ($orWhere) {
                if ($orWhere) $query->orWhere($orWhere);
            })->count();
        $listData = WfCompany::where($where)
            ->where(function ($query) use ($orWhere) {
                if ($orWhere) $query->orWhere($orWhere);
            })
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'asc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = WfUser::where('company_id', $v['id'])->where('user_type', '<>', 2)->first();
            $listData[$k]['username'] = $user->name;
            $listData[$k]['realname'] = $user->realname;
        }

        $jsonData = [
            'list' => $listData,
            'count' => $totalCount
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData);
    }
    
    /**
     * 添加单位平台
     *
     * @name    companyCrd
     *
     * @return 	array                       返回结果
     */
    public function companyCrd(CompanyRequest $request)
    {
        $request->validate('crd');
        $param = $request->all();

        // 唯一校验
        if (WfUser::where('mobile', $param['mobile'])->count()) {
            return $this->jsonReturns(50000, trans('wf.WF-Company-Mobile-Has-Exists'));
        }
        if (WfUser::where('idcard', $param['idcard'])->count()) {
            return $this->jsonReturns(50000, trans('wf.WF-Company-Idcard-Has-Exists'));
        }
        if (WfUser::where('email', $param['email'])->count()) {
            return $this->jsonReturns(50000, trans('wf.WF-Company-Email-Has-Exists'));
        }

        DB::beginTransaction();
        try {
            $model = new WfCompany;
            $model->name = $param['name'];
            $model->short_name = $param['short_name'];
            $model->code = strtoupper($param['code']);
            $model->tag = strtoupper($param['tag']);
            $model->status = $param['status'];
            $model->address = $param['address'] ?? '';
            $model->logo = $param['logo'] ?? '';
            $model->legal = $param['legal'];
            $model->idcard = $param['idcard'];
            $model->mobile = $param['mobile'];
            $model->email = $param['email'];
            $model->created_at = Carbon::now();
            $model->save();

            $user = new WfUser;
            $user->name = 'JSL@' . $param['mobile'];
            $user->email = $param['email'];
            $user->idcard = $param['idcard'];
            $user->mobile = $param['mobile'];
            $user->realname = $param['legal'];
            $solt = Uuid::uuid1()->getHex();
            $user->solt = $solt;
            $user->password = Hash::make('JSL@' . $param['idcard'], ['solt' => $solt]);
            $user->avatar = '';
            $user->status = 1;
            $user->user_type = 1;
            $user->company_id = $model->id;
            $user->parent_id = $model->id;
            $user->created_at = Carbon::now();
            $user->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 根据ID获取单位平台信息
     *
     * @name    getCompanyById
     *
     * @return 	array                       返回结果
     */
    public function getCompanyById(Request $request)
    {
        $id = $request->input('id', 0);
        $data = WfCompany::find($id)->toArray();

        return $this->jsonReturns(10000, $this->success, $data);
    }
    
    /**
     * 删除单位平台（根据ID）
     *
     * @name    companyRmv
     *
     * @return 	array                       返回结果
     */
    public function companyRmv(Request $request)
    {
        $id = $request->input('id');

        DB::beginTransaction();
        try {
            $model = WfCompany::find($id);
            $model->isdel = 1;
            $model->deleted_at = time();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 启用禁用单位平台（根据ID）
     *
     * @name    companySts
     *
     * @return 	array                       返回结果
     */
    public function companySts(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status', 0);

        DB::beginTransaction();
        try {
            $model = WfCompany::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 编辑单位平台
     *
     * @name    companyEdt
     *
     * @return 	array                       返回结果
     */
    public function companyEdt(CompanyRequest $request)
    {
        $request->validate('edt');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = WfCompany::find($param['id']);
            $model->name = $param['name'];
            $model->short_name = $param['short_name'];
            $model->code = strtoupper($param['code']);
            // $model->tag = strtoupper($param['tag']);
            $model->status = $param['status'];
            $model->address = $param['address'] ?? '';
            $model->logo = $param['logo'] ?? '';
            $model->legal = $param['legal'];
            $model->idcard = $param['idcard'];
            $model->mobile = $param['mobile'];
            $model->email = $param['email'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 添加单位架构
     *
     * @name    orgCrd
     *
     * @return 	array                       返回结果
     */
    public function orgCrd(OrgRequest $request)
    {
        $request->validate('crd');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = new WfCompany;
            $model->name = $param['name'];
            $model->short_name = $param['short_name'];
            $model->parent_id = $param['companyID'];
            $model->code = Uuid::uuid1()->getHex();
            $model->tag = Uuid::uuid1()->getHex();
            $model->status = $param['status'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 编辑单位架构
     *
     * @name    orgEdt
     *
     * @return 	array                       返回结果
     */
    public function orgEdt(OrgRequest $request)
    {
        $request->validate('edt');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = WfCompany::find($param['id']);
            $model->name = $param['name'];
            $model->short_name = $param['short_name'];
            $model->status = $param['status'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
    
    /**
     * 删除单位架构
     *
     * @name    orgEdt
     *
     * @return 	array                       返回结果
     */
    public function orgRmv(OrgRequest $request)
    {
        $request->validate('rmv');
        $id = $request->input('id');

        DB::beginTransaction();
        try {
            $model = WfCompany::find($id);
            $model->isdel = 1;
            $model->deleted_at = time();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
}
